var base;

var app = new Vue({
    el: '#attr',
    data: {
        formId: formId,
        formName: formName,
        eventLayout: {},
        hiddens: [{id: '', name: ''}],
        selectValue: '',
        history: [],//历史数据
        isHistory: false,//是否正在撤回历史数据
        attrLayout: {
            id: {
                name: '控件Id',
                type: 'text'
            },
            fieldLabel: {
                name: 'label名称',
                type: 'text'
            }, labelWidth: {
                name: 'label宽度',
                type: 'number'
            }, name: {
                name: '属性名称',
                type: 'text'
            }, type: {
                name: '控件类型',
                type: 'selectList',
                data: TYPE
            }, x: {
                name: 'X坐标',
                type: 'number'
            }, y: {
                name: 'Y坐标',
                type: 'number'
            }, width: {
                name: '宽度',
                type: 'number'
            }, height: {
                name: '高度',
                type: 'number'
            }, value: {
                name: '默认值',
                type: 'text'
            }, validator: {
                name: '检验器',
                type: 'text'
            }, dict: {
                name: '字典',
                type: 'text'
            }, redStar: {
                name: '红星标识',
                type: 'checkbox'
            }, required: {
                name: '是否必填',
                type: 'checkbox'
            }, disabled: {
                name: '是否禁止',
                type: 'checkbox'
            }, tooltipTitle: {
                name: '提示标题',
                type: 'text'
            }, tooltip: {
                name: '提示内容',
                type: 'text'
            }
        },
        selectItem: [{
            id: 'id',
            x: 0,
            y: 0,
            fieldLabel: '1',
            labelWidth: '2',
            name: '3',
            type: '4',
            width: '5',
            height: '6',
            value: '7',
            redStar: true,
            required: true,
            disabled: false,
            tooltip: '',
            tooltipTitle: '',
            validator: '8',
            dict: '9'
        }],
        canvasSelects: [],//存放所有选中的item!!!!
        from: [{items: [{}]}],
        txtForm: "",
        inputForm: ""

    },
    methods: {
        hiddenClick:function(that){
            this.selectItem = that;
        },
        //新增元数据
        newMetaBtEvent: function () {
            Event.initMetaWindow();
        },
        //保存按钮事件
        saveBtEvent: function () {
            var str = JSON.stringify(this.from);
            this.txtForm = this.funFilter(str, this.from);
            recodeId === '' ? Event.saveEvent(this.txtForm) : Event.updateEvent(this.txtForm);
        },
        //控件被更改：控件被更改后，需要添加该控件的必要属性，然后再刷新画布
        widgetChange: function (key) {

            if (key == 'type' || key == 'childType') {
                var thatVue = this;
                var thatWidget = thatVue.selectItem;//from[0].items[this.selectItemIndex];
                var type = thatWidget.type.split('_');
                var childAttr = {}, rootAttr = {};
                if (type.length > 1) {
                    //容器子属性
                    thatWidget ['childType'] = type[1];
                    thatWidget.type = type[0];
                    childAttr = TYPE[type[0] + '_' + type[1]].attr;
                }
                //把容器属性和容器子属性合并起来
                rootAttr = TYPE[type[0]].attr;
                var zAttr = $.extend({}, rootAttr, childAttr);
                //  添加没有的属性
                $.each(zAttr, function (i, v) {
                    var flag = false;
                    $.each(thatWidget, function (key, val) {
                        if (v.name === key) {
                            flag = true;
                            return false;//跳出循环
                        }
                    });
                    if (!flag) {//如果flag = false ，则表示 该控件中没有此属性，需要添加
                        thatWidget[v.name] = v.val;//添加，并赋默认值
                    }
                });
                //删除多余的属性
                $.each(thatWidget, function (key, val) {
                    var flag = false;
                    $.each(zAttr, function (i, v) {
                        if (v.name === key) {
                            flag = true;
                            return false;//跳出循环
                        }
                    });
                    if (!flag) {//如果flag = false ，则表示 该控件中的key属性是多余的，需要剔除
                        delete thatWidget[key];//删除该属性
                    }
                });
                this.refreshAttrLayout(type[0]);//刷新属性和事件栏 ::需要先刷新属性栏，后刷新画布
                this.refreshCanvas();//刷新画布
            }
        },
        refreshForm: function () {
            if (this.from[0].cls + ''.indexOf(this.formId) == -1)
                this.from[0].cls += (" " + this.formId);
            this.refreshCanvas();//刷新画布
        },
        //获取值
        getWidgetAttrValue: function (key) {

            return this.selectItem[key];
        },
        //根据ID获取目标容器:递归
        selectTargetWarp: function (id, items) {
            if (id && items && items.length > 0) {
                for (var i = 0; i < items.length; i++) {
                    var v = items[i];
                    if (v.id == id) {
                        return v;
                    } else if (v['items'] && v['items'].length > 0) {
                        var item = this.selectTargetWarp(id, v['items']);
                        if (item) {
                            return item;
                        }
                    }
                }
            }
        },
        //重绘画布
        refreshCanvas: function (selectItem, key) {
            //处理嵌套！666
            if (key == 'superWidgetId') {
                //1、找到目标容器
                var selectItemId = this.selectItem['id'];
                console.log('开始寻找目标控件,Id is ', this.selectItem['superWidgetId'])
                var targetWarp = this.selectTargetWarp(this.selectItem['superWidgetId'], this.from[0].items);
                console.log('寻找完毕，结果目标控件居然是:', targetWarp)
                if (targetWarp) {
                    //2、找到了目标容器，把当前选择的对象放到目标容器内
                    if (!targetWarp['items']) {
                        targetWarp['items'] = [];
                    }
                    var xItem = $.extend(true, {}, this.selectItem);
                    xItem.x = 1;
                    xItem.y = 1;
                    if (deleteItemById(selectItemId)) {
                        $('#' + selectItemId + 'Drag').remove();
                        $('#' + selectItemId).remove();
                        targetWarp['items'].push(xItem);
                    }
                }
            }
            //处理zIndex:2018年6月15日11:03:01
            else if (key == 'zIndex') {
                var zIndex = this.selectItem['zIndex']
                var style = this.selectItem.style || '';
                if (style && style.indexOf('z-index') > -1) {
                    //去除zIndex
                    var tS = style.substring(style.indexOf('z-index'), style.length);
                    tS = tS.substring(0, tS.indexOf(';') + 1);
                    style = style.replace(tS, '');
                }
                //加上zIndex
                var zIndex = 'z-index:' + zIndex + ';';
                if (style.lastIndexOf(";") != style.length - 1) {
                    zIndex = ";" + zIndex;
                }
                style += zIndex;
                $('#' + this.selectItem.id + 'Drag').css({zIndex: zIndex});
                this.selectItem.style = style;
            }
            //处理必填：2018年6月15日11:03:31
            else if (key == 'required') {
                var color = '';
                if (this.selectItem['required']) {
                    color = 'red';
                }
                var style = this.selectItem.style || '';
                var styleKey = 'color';
                if (style && style.indexOf(styleKey) > -1) {
                    //去除zIndex
                    var tS = style.substring(style.indexOf(styleKey), style.length);
                    tS = tS.substring(0, tS.indexOf(';') + 1);
                    style = style.replace(tS, '');
                }
                if (color) {
                    var tStyle = styleKey + ':' + color + ';';
                    if (style.lastIndexOf(";") != style.length - 1) {
                        tStyle = ";" + tStyle;
                    }
                    style += tStyle;
                    $('#' + this.selectItem.id + 'Drag').css({styleKey: tStyle});
                }
                this.selectItem.style = style;
            }
            //处理选项卡数量（tabNum）
            else if (key == 'tabNum') {
                var num = selectItem[key];//取到当前控件的Num
                var tabName = '';
                switch (selectItem.type) {
                    case 'grouppanel':
                        tabName = 'grouppanelTab';
                        break;
                    case 'tabstrip':
                        tabName = 'tab';
                        break;
                }
                var items = selectItem['items'];
                if (!items || items.length < num) {
                    if (!items) {
                        selectItem['items'] = [];
                    }
                    var diffNum = num - selectItem['items'].length;
                    for (var i = 0; i < diffNum; i++) {
                        var item = drag.getWidgetObj(tabName);
                        selectItem['items'].push(item);
                    }
                }
            }
            else if (key == 'activeTabIndex') {//处理当前激活tab
                var index = selectItem[key];
                if (selectItem.items && selectItem.items.length - 1 >= index) {
                    $.each(selectItem.items, function (i, v) {
                        v.layuiShow = (i == index);
                    })
                }
            }

            //如果是多选的情况下，更新所有选中控件的属性-----------------------
            if (selectItem && this.canvasSelects.length > 1) {
                var item = selectItem;
                $.each(this.canvasSelects, function (i, v) {
                    if (v.id == item.id) {
                        return true;//continue
                    }
                    v[key] && (v[key] = item[key]);
                })
            }
            //如果是多选的情况下，更新所有选中控件的属性----------------------
            drawCanvas(this.from);
            initDrag();
            var selects = this.canvasSelects;
            //需要setTimeout的原因是，需要等Vue把界面渲染完成，才能进行DOM操作
            setTimeout(function () {
                $.each(selects, function (i, v) {
                    $(document).find('#' + v.id + 'Drag').addClass('weightSelect');
                })
            }, 100)
        },


        refreshAttrLayout: function (type) {//刷新属性栏
            console.log('刷新属性栏');
            var attrLay = {};
            //把基本属性加入进来
            $.each(TYPE[type].attr, function (i, v) {
                var name = v.name;
                if (ATTRS[name]) {
                    ATTRS[name]['show'] = v.show;
                    attrLay[name] = ATTRS[name];
                }
            });
            //把基本事件加入进来
            var eventLay = {};
            $.each(TYPE[type].event, function (i, v) {
                var name = v.name;
                if (ATTRS[name]) {
                    ATTRS[name]['show'] = v.show;
                    eventLay[name] = ATTRS[name];
                }
            });

            //如果存在childType （则代表是一个容器），则需要把该容器特有的attr加入进来。
            if (app.selectItem.childType) {

                //添加Class
                var cls = app.selectItem.childType;
                //去掉子TYPE所有的class
                $.each(childTYPE, function (i, v) {
                    app.selectItem.cls = app.selectItem.cls.replace(' ' + i, "");
                })
                app.selectItem.cls += ' ' + cls;
                //加入所有属性
                $.each(TYPE['panel_' + app.selectItem.childType].attr, function (i, v) {
                    attrLay[v.name] = ATTRS[v.name];
                    attrLay[v.name]['show'] = v.show;//设置每个属性是否显示
                })
                //加入所有事件
                TYPE['panel_' + app.selectItem.childType].event && $.each(TYPE['panel_' + app.selectItem.childType].event, function (i, v) {
                    ATTRS[v.name]['show'] = v.show;
                    eventLay[v.name] = ATTRS[v.name];
                })
            }
            this.eventLayout = eventLay;
            this.attrLayout = attrLay;
        },
        alignWidgetEvent: function (e) {
            var that = $(e.currentTarget);
            Event.alignWidgetEvent(that);
            // alert(that.attr('title'))
        },
        funFilter: function (str, from) {//过滤 方法名左右两边的引号

            return str;
        }, revoke: function (event) {
            if (this.history.length == 1) {
                return;
            }
            if (event) {
                this.isHistory = true;
                var index = $(event.path[0]).data('index');
                this.from = this.history[index].data;
            } else {
                this.isHistory = true;
                this.history.splice(this.history.length - 1, 1);
                this.from = this.history[this.history.length - 1].data;
            }

            drawCanvas(this.from);
            initDrag();
        },
        procChild: function (items) {
            return items;

        }
    },
    watch: {
        selectItem: {
            handler: function (val, oldVal) {
                //如果存在childType （则代表是一个容器），则需要把该容器特有的attr加入进来。
                this.refreshAttrLayout(this.selectItem.type);

            }, deep: true
        },
        from: {
            handler: function (val, oldVal) {
                console.log('from监听被触发');
                //填充隐藏表单域列表 start
                this.hiddens = [];
                findItemByType('hidden');
                //填充隐藏表单域列表 end
                //处理嵌套：因为没办法知道是哪个具体的控件发生了嵌套，所以只能遍历Form处理嵌套。
                this.from[0].items = this.procChild(this.from[0].items);

                if (!this.isHistory) {
                    if (this.history.length > 10) {
                        this.history.splice(0, 1);
                    }
                    this.history.push({
                        name: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                        data: $.extend(true, [], this.from)
                    })
                }
                this.isHistory = false;
                var str = JSON.stringify(this.from);
                this.txtForm = this.funFilter(str, this.from);
            }, deep: true//对象内部的属性监听，也叫深度监听
        }, txtForm: {
            handler: function () {
            }
        }, inputForm: {
            handler: function () {
                this.from = JSON.parse(this.inputForm);
                drawCanvas(this.from);
                initDrag();
            }
        }
    }
});

layui.use(['form', 'layedit', 'laydate', 'element'], function () {
    var form = layui.form
        , layer = layui.layer
        , layedit = layui.layedit
        , laydate = layui.laydate
        , layElement = layui.element;
    um.init(form, laydate, layElement);
    if (app.from[0].cls && app.from[0].cls.indexOf(app.formId) == -1) {
        app.from[0].cls += ' ' + app.formId;
    }
    //初始化数据
    app.inputForm = formData;
    initView();
    initWidgetList();
    initKeyUp();
});

/***
 * 初始化键盘事件
 */
function initKeyUp() {
    /***********绑定键盘 移动**************/
    $(document).off();
    $(document).keydown(function (e) {
            var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
            // //用于多选
            drag.cont.isCtrl = (key == 17);
            drag.cont.isShift = (key == 16);
            var ctrlDist = 14;//ctrl键移动的距离
            if (key == 90 && e.ctrlKey) {
                app.revoke();
            }
            if (key == 46) {//delete
                if (app.canvasSelects.length > 1) {
                    alert('请不要选择多个进行删除，会出问题的！表示我也很无奈。')
                    return;
                }
                var i = app.selectItem;
                var id = i.id;
                if (deleteItemById(id)) {
                    $('#' + id + 'Drag').remove();
                    $('#' + id).remove();
                }
                app.canvasSelects = [];
                return;
            }
            if (key == 37) {
                if (e.shiftKey) {
                    $.each(app.canvasSelects, function (index, v) {
                        var i = v;
                        if (!i.width) {
                            console.error('错误！该控件没有宽度属性，请维护宽度属性');
                            return;
                        }
                        var input = getInputWidget(i)
                        var width = drag.util.replacePx(input.css('width'));
                        if (width > 14) {//如果input的宽度小于14，则不再变短
                            e.ctrlKey ? i.width -= ctrlDist : --i.width;
                            var px = (e.ctrlKey ? width -= ctrlDist : --width) + 'px';
                            input.css({'width': px});
                            var widgetItem = findJqItemById(i.id);
                            widgetItem.css({
                                'width': i.width + 'px'
                            });
                        }
                    });
                } else {
                    $.each(app.canvasSelects, function (index, v) {
                        var i = v;
                        var xy = {x: i.x, y: i.y};
                        e.ctrlKey ? xy.x -= ctrlDist : xy.x--;
                        setItemXY(i.id, xy);
                        i.x = xy.x;

                    });
                }
                e.preventDefault();
            }
            /*alert("按了↑键！"); */
            if (key == 38) {
                if (e.shiftKey) {
                    $.each(app.canvasSelects, function (index, v) {
                        var i = v;
                        if (!i.height) {
                            console.log('错误！该控件没有高度属性，请维护高度属性');
                            return;
                        }
                        var input = getInputWidget(i)
                        var height = drag.util.replacePx(input.css('height'));
                        if (height > 27) {//如果input的宽度小于14，则不再变短
                            e.ctrlKey ? i.height -= ctrlDist : --i.height;
                            var px = (e.ctrlKey ? height -= ctrlDist : --height) + 'px';
                            input.css({'height': px});
                            var widgetItem = findJqItemById(i.id);
                            widgetItem.css({
                                'height': i.height + 'px'
                            });
                        }
                    });
                } else {
                    $.each(app.canvasSelects, function (index, v) {
                        var i = v;
                        var xy = {x: i.x, y: i.y};
                        e.ctrlKey ? xy.y -= ctrlDist : xy.y--;
                        setItemXY(i.id, xy);
                        i.y = xy.y;
                    });
                }
                e.preventDefault();
            }
            /*alert("按了→键！"); */
            if (key == 39) {
                if (e.shiftKey) {
                    $.each(app.canvasSelects, function (index, v) {
                        var i = v;
                        if (!i.width) {
                            console.log('错误！该控件没有宽度属性，请维护宽度属性');
                            return;
                        }
                        var input = getInputWidget(i)
                        var width = drag.util.replacePx(input.css('width'));
                        e.ctrlKey ? i.width += ctrlDist : ++i.width;
                        var px = (e.ctrlKey ? width += ctrlDist : ++width) + 'px';
                        input.css({'width': px});
                        var widgetItem = findJqItemById(i.id);
                        widgetItem.css({
                            'width': i.width + 'px'
                        });
                    });
                } else {
                    $.each(app.canvasSelects, function (index, v) {
                        var i = v;
                        var xy = {x: i.x, y: i.y};
                        e.ctrlKey ? xy.x += ctrlDist : xy.x++;
                        setItemXY(i.id, xy);
                        i.x = xy.x;
                    });
                }
                e.preventDefault();
            }
            /*alert("按了↓键！"); */
            if (key == 40) {
                if (e.shiftKey) {
                    $.each(app.canvasSelects, function (index, v) {
                        var i = v;
                        if (!i.height) {
                            console.log('错误！该控件没有高度属性，请维护高度属性');
                            return;
                        }
                        var input = getInputWidget(i)
                        var height = drag.util.replacePx(input.css('height'));
                        e.ctrlKey ? i.height += ctrlDist : ++i.height;
                        var px = (e.ctrlKey ? height += ctrlDist : ++height) + 'px';
                        input.css({'height': px});
                        var widgetItem = findJqItemById(i.id);
                        widgetItem.css({
                            'height': i.height + 'px'
                        });
                    });
                } else {
                    $.each(app.canvasSelects, function (index, v) {
                        var i = v;
                        var xy = {x: i.x, y: i.y};
                        e.ctrlKey ? xy.y += ctrlDist : xy.y++;
                        setItemXY(i.id, xy);
                        i.y = xy.y;
                    });
                }
                e.preventDefault();
            }

        }
    );
    $(document).keyup(function (e) {
        var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        log(key)
        if (key == 17) {
            log('ctrl弹起');
            drag.cont.isCtrl = !(key == 17);
            log(drag.cont.isCtrl)
        }
        if (key == 16) {
            log('shift弹起');
            drag.cont.isShift = !(key == 16);
            log(drag.cont.isCtrl)
        }


    });
    /***********绑定键盘事件移动结束**************/
}


function getInputWidget(i) {
    var input = $('#' + i.id).find('[name="' + i.name + '"]');
    if (!input[0]) {//如果没有name控件，则取本身。
        input = $('#' + i.id);
    }
    return input;
}

/**
 * 界面初始化
 */
function initView() {

    layx.html('tool', '工具栏', $('#rulerCtrlPand')[0], {
        cloneElementContent: false,
        storeStatus:false,
        mergeTitle: false,
        width: '255',
        height: '172',
        minHeight: 150,
        position: ['t'],
        leftOut: false,
        rightOut: false,
        topOut: false,
        bottomOut: false,
        closable: false,
        closeMenu: false,
        debugMenu: false,
        minable: true,
        minMenu: true,
        stickMenu: false,
        maxMenu: false,
        isOverToMax: false,
        dragInTopToMax: false
    });
    layx.html('formObj', 'From对象', $('#textCode')[0], {
        cloneElementContent: false,
        mergeTitle: false,
        storeStatus:false,
        width: '450',
        height: '275',
        position: ['cb', 500],
        leftOut: false,
        rightOut: false,
        topOut: false,
        bottomOut: false,
        closable: false,
        closeMenu: false,
        debugMenu: false,
        minable: true,
        minMenu: true,
        stickMenu: false,
        maxMenu: false,
        isOverToMax: false,
        dragInTopToMax: false,
        event:{
            onload:{
                before: function (layxWindow, winform) {
                    layx.min('formObj');
                }
            },
        }
    });

    layx.html('history', '历史记录', $('#history')[0], {
        cloneElementContent: false,
        mergeTitle: false,
        storeStatus:false,
        width: '11%',
        height: '25%',
        position: ['cb', 200],
        leftOut: false,
        rightOut: false,
        topOut: false,
        bottomOut: false,
        closable: false,
        closeMenu: false,
        debugMenu: false,
        minable: true,
        minMenu: true,
        stickMenu: false,
        maxMenu: false,
        isOverToMax: false,
        dragInTopToMax: false,
        event:{
            onload:{
                before: function (layxWindow, winform) {
                    layx.min('history');
                }
            },
        }
    });

    layx.html('hiddens', '隐藏表单域列表', $('#hiddens')[0],
        {
            cloneElementContent: false,
            mergeTitle: false,
            storeStatus:false,
            title: '隐藏表单域列表',
            width: '11%',
            height: '50%',
            position: 't',
            leftOut: false,
            rightOut: false,
            topOut: false,
            bottomOut: false,
            closable: false,
            closeMenu: false,
            debugMenu: false,
            minable: true,
            minMenu: true,
            stickMenu: false,
            maxMenu: false,
            isOverToMax: false,
            dragInTopToMax: false,
            event:{
                onload:{
                    before: function (layxWindow, winform) {
                        layx.min('hiddens');
                    }
                },
            }
        }
    );
    layx.group(
        'layx', [
            {
                id: 'attr',
                title: '属性',
                cloneElementContent: false,
                content: $('#attrPanel')[0]
            }, {
                id: 'event',
                title: '事件',
                cloneElementContent: false,
                content: $('#eventPanel')[0]
            }
        ], 0,
        {
            storeStatus:false,
            mergeTitle: false,
            title: '属性面板',
            width: '11%',
            height: '98%',
            position: 'rt',
            leftOut: false,
            rightOut: false,
            topOut: false,
            bottomOut: false,
            closable: false,
            closeMenu: false,
            debugMenu: false,
            minable: true,
            minMenu: true,
            stickMenu: false,
            maxMenu: false,
            isOverToMax: false,
            dragInTopToMax: false
        }
    );

}

/**
 * 绘制画布
 * @Date 2018年2月22日12:24:43
 * @param from Js对象
 */
function drawCanvas(from) {
    //画布DIV的Id是 canvas
    $('.canvas').html('');
    var f = $.extend(true, [], from);
    um.ui(f[0])
}

/**
 * 初始化拖动
 */
function initDrag() {
    //延时是为了等F.js把界面渲染完成了再开始。
    if (app.from[0].items.length == 0) {
        return
    }
    setTimeout(function () {
        drag.init({
            elm: '.widgetItem',
            event: {
                //主面板点击事件
                panelClickCallback: function () {
                    //如果没有选中的，则不操作
                    if (app.canvasSelects.length != 0) {
                        //把当前选中的item设置成空
                        app.selectItem = {};
                        //把Index设置为0
                        // app.selectItemIndex = 0;
                        //1、清空画布多选的数组
                        app.canvasSelects = [];
                        //刷新画布
                        app.refreshCanvas();
                        app.eventLayout = {};
                        app.attrLayout = {};
                    }
                },
                //初始化完成回调事件
                initCallback: function () {

                },
                //开始移动回调事件
                startMoveCallback: function (current, e) {

                },
                //移动中回调事件
                moveCallback: function (a, b, c) {

                },
                //结束移动回调事件
                stopMoveCallback: function (a, b, wL, wT) {
                    var id = drag.util.replaceDrag($(a.target).attr('id'));
                    var item = findItemById(id);
                    item.x = wL;
                    item.y = wT;
                },
                //大小被改变事件
                resize: function () {

                },
                stopResize: function (target, w, h) {
                    var id = drag.util.replaceDrag(target.attr('id'));
                    app.selectItem = findItemById(id);
                    if (h != -1) app.selectItem.height = h;
                    if (w != -1) app.selectItem.width = w;
                    app.refreshCanvas();
                },
                //开始拖动大小回调事件
                startResize: function () {

                },
                //控件被单击回调事件
                widgetClick: function (thats, that, isMulti) {
                    //情况1：子控件已经选中，点击该子控件的父容器
                    if (that.find('.weightSelect')[0]) {
                        that.find('.weightSelect').each(function (i, v) {
                            $(this).removeClass('weightSelect');
                        });
                    }

                    //情况2：如容器已经选中，点击子控件
                    if (that.parents('.weightSelect')[0]) {
                        that.parents('.weightSelect').each(function (i, v) {
                            $(this).removeClass('weightSelect');
                            app.canvasSelects = [];
                        });
                    }

                    //找到当前点击的控件
                    var id = drag.util.replaceDrag(that.attr('id'));
                    console.log('当前控件ID:' + id)
                    var item = findItemById(id);
                    if (!item) {
                        console.error('没有此控件：' + id);
                        return;
                    }
                    app.selectItem = item;
                    //画布多选部分
                    //1、如果没有按住Ctrl,则不是多选，需清空画布多选的数组
                    if (!drag.cont.isCtrl) {
                        app.canvasSelects = [];
                    }
                    //2、把当前选中的控件放入多选数组中
                    var id = drag.util.replaceDrag(that.attr('id'));
                    app.canvasSelects.push(findItemById(id));
                    ///刷新属性栏
                    // var widget = app.selectItem;针对隐藏表单域的特殊处理
                    // var type = isHidden(widget.cls) ? 'hidden' : widget.type;//
                    // app.refreshAttrLayout(type);//刷新属性栏
                },
                //删除控件的回调
                closeEvent: function (id) {
                    if (deleteItemById(id)) {
                        F(id).hide();
                        $('#' + id + 'Drag').remove();
                        $('#' + id).remove();
                    }
                },
                //主面板尺寸被改变
                mianPanelSizeChange: function (width, height) {
                    console.log(width, height)
                    app.from[0].width = width;
                    app.from[0].height = height;
                }
            }

        });
        um.ui("inc007").loadData([{name: '777', value: '123', selected: ''}, {
            name: '777',
            value: '123',
            selected: ''
        }, {name: '778', value: '123', selected: ''}, {name: '78998', value: '123', selected: ''}]);
    }, 100)
}

function initWidgetList() {
    drag.initWidgetList(function (widget) {
       /* var item = $.extend(true, {}, widget);
        /!******针对面板的特殊处理****************!/
        if (widget.type == 'panel') {//针对容器的特殊处理
            item['cls'] += ' ' + item.childType;
        }
        app.from[0].items.push(item);
        var fItem = $.extend(true, {}, item);
        /!**************************************!/
        //针对隐藏表单域的特殊处理
        if (widget.type === 'hidden') {
            fItem = initOneHidden(fItem, item);
        }
        //针对隐藏表单域的特殊处理
        /!**************************************!/
        app.refreshCanvas();
        //回调函数*/


        var item = $.extend(true, {}, widget);
        /******针对面板的特殊处理****************/
        if (widget.type == 'panel') {//针对容器的特殊处理
            item['cls'] += ' ' + item.childType;
        }
        app.from[0].items.push(item);
        //回调函数
    }, '#canvas');
}


/***
 * 根据类型查询items。  递归！
 * @param id
 * @returns item
 */
function findItemByType(type, items, hiddens) {

    if (!items) {
        items = app.from[0].items;
    }
    if (!hiddens) {
        hiddens = app.hiddens;
    }
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (item.type == type) {
            hiddens.push(item);
        } else if (item['items'] && item['items'].length > 0) {
            findItemByType(type, item['items']);
        }
    }

}


/**
 * 设置Item的XY
 *xy:{x:1,y:2}
 * **/
function setItemXY(itemId, xy) {
    log('设置Item的XY--------------')
    log(itemId)
    log(xy)
    log('设置Item的XY--------------')
    $('#' + itemId + 'Drag').css({
        top: xy.y,
        left: xy.x
    })
}

/***
 * 初始化一个隐藏表单域
 * @param fItem
 * @returns {*}
 */
function initOneHidden(fItem, item) {
    fItem.value = item.name + "=" + item.value;
    fItem.width = 100;
    fItem.height = 47;
    fItem.type = 'textbox';
    return fItem;
}

/***
 * 根据ID删除Item::递归！
 *
 * */
function deleteItemById(id, items) {
    if (!items) {
        items = app.from[0].items;
    }
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (item.id == id) {
            items.splice(i, 1);
            app.textCode = app.from[0];
            return true;
        } else {
            if (item['items'] && item['items'].length > 0) {
                var flag = deleteItemById(id, item['items']);
                if (flag) {
                    return true;
                }
            }
        }
    }
    return false;
}

/***
 * 根据id查询item。  递归！
 * @param id
 * @returns item
 */
function findItemById(id, items) {
    if (!items) {
        items = app.from[0].items;
    }
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (item.id == id) {
            return item;
        } else if (item['items'] && item['items'].length > 0) {
            var item = findItemById(id, item['items']);
            if (item) {
                return item;
            }
        }
    }

}

/***
 * 根据控件ID获取Jq对象
 * @param id
 * @returns {jQuery|HTMLElement}
 */
function findJqItemById(id) {
    return $('#' + id + 'Drag');
}

/***
 * 针对隐藏表单域的特殊处理
 * 判断Class中是否包含Hidden
 * */
function isHidden(cls) {
    if (cls && cls != '' && cls.indexOf('hidden') > -1) {
        return true;
    }
    return false;
}

/**输出调试信息***/
var isDebug = true;

function log(log) {
    isDebug && console.log(log);
}


var Event = {
    //新增元数据第一步：选择表名
    initMetaWindow: function () {
        var loadDataNum = 0;
        var loadData;
        var windowId = 'selectMetaSou';
        F.ui({
            type: 'window',
            modal: false,
            id: windowId,
            renderTo: document.body,
            width: 422,
            height: 175,
            bodyPadding: 0,
            autoScroll: true,
            title: '选择数据源',
            resizable: true,
            closable: false,
            items: [{
                "tableStyle": false,
                "header": false,
                "type": "form",
                "id": "form1",
                "cls": 1521200674912,
                "width": 420,
                "height": 100,
                "layout": "absolute",
                "bodyPadding": 5,
                "collapsible": true,
                "title": "表单 2",
                "items": [{
                    "id": "metaWidget",
                    "fieldLabel": "元数据",
                    "labelWidth": 63,
                    "width": 350,
                    "x": 26,
                    "y": 24,
                    "clearIcon": true,
                    "multiSelectSeparator": ",",
                    "maxPopHeight": "300",
                    type: 'dropdownbox', matchFieldWidth: false,
                    emptyText: '请从下拉表格中选择',
                    multiSelect: true,
                    popPanel: {
                        type: 'grid',
                        id: 'grid1000',
                        hidden: true,
                        width: 460,
                        height: 300,
                        header: false,
                        checkboxSelect: true,
                        multiSelect: true,
                        keepCurrentSelection: true,
                        paging: false,
                        databasePaging: false,
                        columns: [{
                            text: '表名', field: 'name', width: 200
                        }, {
                            text: '中文名', field: 'comment', width: 180
                        }],
                        idField: 'name',
                        textField: 'name',
                        dataUrl: '/manage/metadata/getTabs',
                        listeners: {
                            dataload: function () {
                                loadDataNum++;
                                if (loadDataNum == 1) {
                                    loadData = F('grid1000').data;
                                }
                            }
                        },
                        bars: [{
                            type: 'toolbar', align: 'left',
                            items: [{
                                type: 'textbox',
                                id: 'triggerbox1',
                                width: 300,
                                hideLabel: true,
                                emptyText: '在表名中查找',
                                trigger1Hidden: true,
                                listeners: {
                                    change: function () {
                                        var key = this.getValue();
                                        key == ''
                                            ?
                                            F('grid1000').loadData(loadData)
                                            :
                                            F('grid1000').loadData(
                                                $.map(loadData, function (item, index) {
                                                    if (item.text.indexOf(key) > -1) {
                                                        return item;
                                                    } else {
                                                        return null;
                                                    }
                                                })
                                            )
                                    }
                                }
                            }]
                        }]
                    }
                }]
            }],
            bars: [{
                type: 'toolbar', align: 'right', position: 'bottom',
                items: [{
                    type: 'button', text: '确定', validateForm: 'form1',
                    handler: function () {
                        var metaWidget = F('metaWidget');
                        var value = metaWidget.getText();
                        if (value != '') {
                            Event.initMetaWindowTow(value);
                            // showNotify(metaWidget.getText());
                            F(windowId).hide();
                        } else {
                            showNotify('下拉框为空');
                        }
                    }
                }, {
                    type: 'button', text: '关闭窗体',
                    handler: function () {
                        F(windowId).hide();
                    }
                }]
            }]
        })

    },
    //第二步：根据表名获取元数据
    initMetaWindowTow: function (val) {
        var windowId = 'selectMetaSouTow';
        F.ui({
            type: 'window',
            id: windowId,
            renderTo: document.body,
            hidden: false,
            width: 500,
            height: 350,
            layout: 'hbox',
            bodyPadding: 5,
            title: '列配置（双击行显示隐藏）',
            iconFont: 'f-iconfont-group',
            items: [{
                type: 'grid',
                id: 'grid2',
                marginRight: 5,
                showSelectedCell: true,
                cellEditing: true,
                flex: 1,
                header: false,
                columnMenu: false,
                multiSelect: true,
                listeners: {
                    rowdblclick: function (event, rowId) {
                        var gridConfig = F.ui.grid2;
                        var rowData = gridConfig.getRowData(rowId);
                        var toggledShow = !rowData.values['key'];
                        gridConfig.updateCellValue(rowData, 'key', toggledShow, true);
                        gridConfig.commitChanges();

                    }
                },
                columns: [{
                    columnType: 'rownumberfield', field: 'rowNumber'
                }, {
                    text: 'ID', field: 'name'
                }, {
                    text: '名称', field: 'comment', flex: 1, editable: true,
                    editor: {
                        type: 'textbox', required: true
                    }
                }, {
                    text: '是否隐藏域', field: 'key', columnType: 'checkboxfield'
                }],
                dataUrl: '/manage/metadata/getColumn/' + val,
                idField: 'name'
            }, {
                type: 'panel', width: 120, layout: 'vbox', border: false, header: false,
                items: [{
                    type: 'button', marginBottom: 5, text: '确认',
                    listeners: {
                        click: function (event) {
                            var data = $.map(F('grid2').data, function (item, index) {
                                return {
                                    id: item.id,
                                    name: item.values['comment'],
                                    isHidden: item.values['key']
                                }
                            });
                            //把元数据插入到画布中
                            Event.insertData(data);
                            F(windowId).hide();
                        }
                    }
                }, {
                    type: 'button', marginBottom: 20, text: '删除选中',
                    listeners: {
                        click: function (event) {
                            var gridConfig = F.ui.grid2;
                            gridConfig.deleteSelectedRows();
                            gridConfig.commitChanges();

                        }
                    }
                }, {
                    type: 'button', marginBottom: 5, text: '关闭',
                    listeners: {
                        click: function (event) {
                            F(windowId).hide();
                        }
                    }
                }]
            }]
        });


    },
    //第三部：把元数据插入到画布中
    insertData: function (data) {
        var xHiddenArray = [];
        var xWidgetArray = [];
        $.each(data, function (i, v) {
            var widgetItem = {};
            if (v.isHidden) {
                widgetItem = drag.getWidgetObj('hidden');
                widgetItem.fieldLabel = v.name.substr(0, 5);
            } else {
                widgetItem = drag.getWidgetObj('textbox');
                widgetItem.fieldLabel = v.name;
            }

            widgetItem.id = v.id;
            widgetItem.name = v.id;
            widgetItem.x = 10;
            widgetItem.y = 10;
            if (v.isHidden) {
                xHiddenArray.push(widgetItem);
            } else {
                xWidgetArray.push(widgetItem);
            }
        })
        var xDefVal = 10;
        var x = xDefVal, y = 10;
        var yDis = 32;
        var xDis = 210;
        $.each(xWidgetArray, function (i, v) {
            if (i != 0) {
                x += xDis;
                if ((i) % 3 == 0) {
                    x = xDefVal;
                    y += yDis;
                }
            } else {

            }
            v.x = x;
            v.y = y;
            app.from[0].items.push(v);
        });

        xDefVal = 10;
        var yDefVal = 700;
        x = xDefVal;
        y = yDefVal;
        yDis = 20;
        xDis = 110;
        $.each(xHiddenArray, function (i, v) {
            if (i != 0) {
                x += xDis;
                if ((i) % 5 == 0) {
                    x = xDefVal;
                    y += yDis;
                }
            } else {

            }
            v.x = x;
            v.y = y;
            app.from[0].items.push(v);
        });
        F.alert('插入成功');
        app.refreshCanvas();
        /*

         var itemWidget = $.extend(true, {},drag.cont.widget);
         log(itemWidget)
         itemWidget.id = 'widget' + F.ui.form.items.length;
         itemWidget.name = 'widget' + F.ui.form.items.length;
         */
    },
    saveEvent: function (dataForm) {
        var data = {
            fta001: app.from[0].id,
            fta002: dataForm,
            fta003: app.from[0].title
        }
        CZ_Ajax.ajax({
            url: '/manage/form/create',
            type: 'post',
            data: JSON.stringify(data),
            callback: function (res) {
                if (res.code == 1) {
                    F.alert('操作成功');
                    F.activeWindow.hideRefresh();
                } else {
                    F.alert(data.data);
                }

            }
        });
    },
    updateEvent: function (dataForm) {

        var data = {
            fta000: recodeId,
            fta001: app.from[0].id,
            fta002: dataForm,
            fta003: app.from[0].title
        }
        CZ_Ajax.ajax({
            type: 'post',
            url: '/manage/form/update/',
            data: JSON.stringify(data),
            callback: function (res) {
                if (res.code == 1) {
                    F.alert('操作成功');
                    F.activeWindow.hideRefresh();
                } else {
                    F.alert(data.data);
                }
            }
        });
    },
    //对齐控件
    alignWidgetEvent: function (that) {
        var type = that.attr('title');
        var list = app.canvasSelects;

        if (list.length < 2) {
            layx.msg('选择两个以上控件进行操作');
            return;
        }
        var targetItem = list[0];
        if (type == '顶端对齐') {
            for (var i = 1; i < list.length; i++) {
                var item = list[i];
                item.y = targetItem.y;
                $('#' + item.id + 'Drag').css({top: item.y});
            }
            return;
        }
        else if (type == '横向居中对齐') {
            for (var i = 1; i < list.length; i++) {
                var item = list[i];
                //取Target的高度/2，得到中间值，中间值减去当前控件高度的一半
                item.y = (targetItem.y + findJqItemById(targetItem.id).height() / 2) - (findJqItemById(item.id).height() / 2);
                $('#' + item.id + 'Drag').css({top: item.y});
            }
            return;
        }
        else if (type == '底端对齐') {
            var targetBottomY = targetItem.y + findJqItemById(targetItem.id).height();//目标对象的底部Y坐标
            for (var i = 1; i < list.length; i++) {
                var item = list[i];
                item.y = targetBottomY - findJqItemById(item.id).height();
                $('#' + item.id + 'Drag').css({top: item.y});
            }
            return;

        }
        else if (type == '左对齐') {
            for (var i = 1; i < list.length; i++) {
                var item = list[i];
                item.x = targetItem.x;
                $('#' + item.id + 'Drag').css({left: item.x});
            }
        }
        else if (type == '垂直居中对齐') {
            for (var i = 1; i < list.length; i++) {
                var item = list[i];
                //取Target的宽度/2，得到中间值，中间值减去当前控件宽度的一半
                item.x = (targetItem.x + findJqItemById(targetItem.id).width() / 2) - (findJqItemById(item.id).width() / 2);
                $('#' + item.id + 'Drag').css({left: item.x});
            }
            return;
        }
        else if (type == '右对齐') {
            var targetRightX = targetItem.x + findJqItemById(targetItem.id).width();//目标对象的底部Y坐标
            for (var i = 1; i < list.length; i++) {
                var item = list[i];
                item.x = targetRightX - findJqItemById(item.id).width();
                $('#' + item.id + 'Drag').css({left: item.x});
            }
            return;
        }
        else if (type == '顶端分布') {
            var maxTop = 99999, maxBottom = 0;
            //获取控件范围的最顶部和最底部
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                //寻找最大的顶点
                if (item.y < maxTop) {
                    maxTop = item.y;
                }
                //寻找最大的底点
                if (item.y + findJqItemById(item.id).height() > maxBottom) {
                    maxBottom = item.y + findJqItemById(item.id).height();
                }
            }
            //进行一个排序，把Y坐标最小的放最前面
            list = list.sort(function (a, b) {
                return a.y > b.y
            });
            console.log(list)
            var totalDiff = (maxBottom - maxTop);//总高度
            $.each(list, function (i, v) {
                totalDiff -= findJqItemById(v.id).height();
            });
            var diff = totalDiff / (list.length - 1);//差距
            for (var i = 1; i < list.length; i++) {//从第二个开始
                var item = list[i];
                var h = 0;
                for (var j = 0; j < i; j++) {
                    var jItem = list[j];
                    h += findJqItemById(jItem.id).height();
                }
                var cDiff = diff * i;//总间距
                item.y = cDiff + h + maxTop;
                setItemXY(item.id, {y: item.y});
            }
            return;
        } else if (type == '横向居中分布') {

        } else if (type == '底端分布') {

        } else if (type == '左端分布') {
            var left = 99999, right = 0;
            //获取控件范围的最顶部和最底部
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                console.log(item.x)
                if (item.x < left) {
                    left = item.x;
                }

                if (item.x + findJqItemById(item.id).width() > right) {
                    right = item.x + findJqItemById(item.id).width();
                }
            }
            //进行一个排序，把Y坐标最小的放最前面
            list = list.sort(function (a, b) {
                return a.x > b.x
            });
            var totalDiff = (right - left);//总高度
            $.each(list, function (i, v) {
                totalDiff -= findJqItemById(v.id).width();
            });
            var diff = totalDiff / (list.length - 1);//差距
            for (var i = 1; i < list.length; i++) {//从第二个开始
                var item = list[i];
                var w = 0;
                for (var j = 0; j < i; j++) {
                    var jItem = list[j];
                    w += findJqItemById(jItem.id).width();
                }
                var cDiff = diff * i;//总间距
                item.x = cDiff + w + left;
                setItemXY(item.id, {x: item.x});
            }

        } else if (type == '垂直居中分布') {

        } else if (type == '右端分布') {

        }

    }
}


// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
